package com.java.auth.service.impl;

import com.java.auth.service.SysMenuService;
import com.java.auth.service.SysUserService;
import com.java.model.system.SysUser;
import com.java.auth.pojo.CustomUser;

import com.java.auth.service.UserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getByUsername(s);
        if(null == sysUser) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        if(sysUser.getStatus().intValue() == 0) {
            throw new RuntimeException("账号已停用");
        }
        List<String> permsByUserId = sysMenuService.findPermsByUserId(sysUser.getId());
        List<SimpleGrantedAuthority> authority = new ArrayList<>();
        for(String perm:permsByUserId){
            authority.add(new SimpleGrantedAuthority(perm.trim()));
        }
        return new CustomUser(sysUser, authority);
    }
}
